import '../../models/ceramic_stage_model.dart';
import '../services/database_service.dart';

class CeramicStageRepository {
  final DatabaseService _databaseService = DatabaseService();

  // 表名
  final String _tableName = 'ceramic_stages';

  // 获取所有使用烧制计时的数据
  Future<List<Map<String, dynamic>>> getAllTimerUsage() async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> result = await db.rawQuery('''
        SELECT 
          cs.id as stage_id, 
          cs.ceramic_id,
          cs.type, 
          cs.status,
          cs.duration_seconds,
          cs.start_time,
          cs.end_time,
          cs.created_at as cs_created_at,
          cs.updated_at as cs_updated_at,
          
          c.id as ceramic_id, 
          c.user_id,
          c.title,
          c.description,
          c.image_url,
          c.is_skipped,
          c.like_count,
          c.favorite_count,
          c.created_at as c_created_at,
          c.updated_at as c_updated_at,
          
          u.id as user_id,
          u.username,
          u.nickname,
          u.avatar,
          u.created_at as u_created_at,
          u.updated_at as u_updated_at
        FROM 
          $_tableName cs
        JOIN 
          ceramics c ON cs.ceramic_id = c.id
        JOIN 
          users u ON c.user_id = u.id
        WHERE 
          cs.start_time IS NOT NULL AND
          c.is_skipped = 0
        ORDER BY 
          cs.start_time DESC
      ''');

      return result;
    } catch (e) {
      print('查询烧制计时数据失败: $e');
      return [];
    }
  }

  // 获取最近使用烧制计时的数据
  Future<List<Map<String, dynamic>>> getRecentTimerUsage(int limit) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> result = await db.rawQuery(
        '''
        SELECT 
          cs.*, c.*, u.*,
          cs.id as stage_id, 
          c.id as ceramic_id, 
          u.id as user_id
        FROM 
          $_tableName cs
        JOIN 
          ceramics c ON cs.ceramic_id = c.id
        JOIN 
          users u ON c.user_id = u.id
        WHERE 
          cs.start_time IS NOT NULL AND
          c.is_skipped = 0
        ORDER BY 
          cs.start_time DESC
        LIMIT ?
      ''',
        [limit],
      );

      return result;
    } catch (e) {
      print('查询最近烧制计时数据失败: $e');
      return [];
    }
  }

  // 为陶瓷作品创建所有阶段
  Future<List<CeramicStage>> createStagesForCeramic(int ceramicId) async {
    final db = await _databaseService.database;
    final now = DateTime.now();
    final List<CeramicStage> stages = [];

    // 创建六个阶段
    for (var i = 0; i < 6; i++) {
      final stage = CeramicStage(
        ceramicId: ceramicId,
        type: CeramicStageType.values[i],
        status: CeramicStageStatus.pending,
        createdAt: now,
        updatedAt: now,
      );

      final id = await db.insert(_tableName, stage.toJson());
      stages.add(stage.copyWith(id: id));
    }

    return stages;
  }

  // 获取陶瓷作品的所有阶段
  Future<List<CeramicStage>> getStagesByCeramicId(int ceramicId) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'ceramic_id = ?',
      whereArgs: [ceramicId],
      orderBy: 'type ASC',
    );

    return List.generate(maps.length, (i) => CeramicStage.fromJson(maps[i]));
  }

  // 获取特定阶段
  Future<CeramicStage?> getStageById(int id) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return CeramicStage.fromJson(maps.first);
    }
    return null;
  }

  // 更新阶段
  Future<int> updateStage(CeramicStage stage) async {
    final db = await _databaseService.database;
    return await db.update(
      _tableName,
      stage.toJson(),
      where: 'id = ?',
      whereArgs: [stage.id],
    );
  }

  // 开始阶段
  Future<CeramicStage?> startStage(int stageId) async {
    final db = await _databaseService.database;
    final stage = await getStageById(stageId);

    if (stage == null) return null;

    final now = DateTime.now();
    final updatedStage = stage.copyWith(
      status: CeramicStageStatus.running,
      startTime: now,
      updatedAt: now,
    );

    final result = await db.update(
      _tableName,
      updatedStage.toJson(),
      where: 'id = ?',
      whereArgs: [stageId],
    );

    return result > 0 ? updatedStage : null;
  }

  // 完成阶段
  Future<CeramicStage?> completeStage(int stageId) async {
    final db = await _databaseService.database;
    final stage = await getStageById(stageId);

    if (stage == null || stage.startTime == null) return null;

    final now = DateTime.now();
    final durationSeconds = now.difference(stage.startTime!).inSeconds;

    final updatedStage = stage.copyWith(
      status: CeramicStageStatus.completed,
      endTime: now,
      durationSeconds: durationSeconds,
      updatedAt: now,
    );

    final result = await db.update(
      _tableName,
      updatedStage.toJson(),
      where: 'id = ?',
      whereArgs: [stageId],
    );

    return result > 0 ? updatedStage : null;
  }

  // 检查所有阶段是否已完成
  Future<bool> areAllStagesCompleted(int ceramicId) async {
    final stages = await getStagesByCeramicId(ceramicId);

    if (stages.isEmpty) return false;

    return stages.every(
      (stage) => stage.status == CeramicStageStatus.completed,
    );
  }

  // 删除陶瓷作品的所有阶段
  Future<int> deleteStagesByCeramicId(int ceramicId) async {
    final db = await _databaseService.database;
    return await db.delete(
      _tableName,
      where: 'ceramic_id = ?',
      whereArgs: [ceramicId],
    );
  }

  // 获取用户的所有陶瓷作品和阶段
  Future<List<Map<String, dynamic>>> getUserCeramics(int userId) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> result = await db.rawQuery(
        '''
        SELECT 
          cs.id as stage_id, 
          cs.ceramic_id,
          cs.type, 
          cs.status,
          cs.duration_seconds,
          cs.start_time,
          cs.end_time,
          cs.created_at as cs_created_at,
          cs.updated_at as cs_updated_at,
          
          c.id as ceramic_id, 
          c.user_id,
          c.title,
          c.description,
          c.image_url,
          c.is_skipped,
          c.is_completed,
          c.like_count,
          c.favorite_count,
          c.created_at as c_created_at,
          c.updated_at as c_updated_at
        FROM 
          ceramics c
        JOIN 
          $_tableName cs ON cs.ceramic_id = c.id
        WHERE 
          c.user_id = ? AND
          c.is_skipped = 0
        ORDER BY 
          c.created_at DESC,
          cs.type ASC
      ''',
        [userId],
      );

      return result;
    } catch (e) {
      print('查询用户陶瓷作品失败: $e');
      return [];
    }
  }
}
